package ru.surfstudio.graduate.parser;

import java.util.ArrayList;


import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import ru.surfstudio.graduate.data.Channel;
import ru.surfstudio.graduate.exception.ParseException;

public class ChannelSearchParser extends Parser<ArrayList<Channel>> {

	private static final long serialVersionUID = 1L;
	
	private static final String TAG = "ChannelSearchParser";
	
	private static final String RESPONSE_DATA = "responseData";
	
	private static final String QUERY = "query";
	
	private static final String ENTRIES = "entries";
	
	private static final String URL = "url";
	
	private static final String TITLE = "title";
	
	private static final String CONTENT_SNIPPET = "contentSnippet";
	
	private static final String LINK = "link";
	
	@Override
	public ArrayList<Channel> parse(String responseString) throws ParseException {
		try {
			Log.d(TAG, "start parsing");
			ArrayList<Channel> resultList = new ArrayList<Channel>();
			
			Log.d(TAG, " parsing step 1");
			JSONObject response = new JSONObject(responseString);
			JSONObject responseData = response.getJSONObject(RESPONSE_DATA);
			JSONArray entries = responseData.getJSONArray(ENTRIES);
			Log.d(TAG, " parsing step 2");
			for (int i = 0; i < entries.length(); i++) {
				JSONObject entry = entries.getJSONObject(i);
				
				Channel channel = new Channel();
				channel.setName(removeHTMLTags(entry.getString(TITLE)));
				channel.setUrl(entry.getString(URL));
				resultList.add(channel);
			}
			Log.d(TAG, " parsing step 3");
			return resultList;
		} catch (Exception e) {
			throw new ParseException(e.getMessage(), e);
		}
	}

}
